<?php
$path = __DIR__."/../../../";
require_once($path.'_inc/app.php');

$dBbooks = Db::getModel("books");
$dBgenre = Db::getModel("genre");

function grubb_book($dBbooks,$dBgenre){
	$id = $dBbooks->getMaxId() + 1;

	//получаем страницу
	$data = file_get_contents("http://www.loveread.ec/view_global.php?id=$id");

	if($data){
		$data = iconv("windows-1251", "UTF-8", $data);
		$data = str_replace(array("\r\n", "\r", "\n",'\t'), '', $data); 
		$data =  preg_replace('/\s{2,}/',' ',$data);
		
		 preg_match("/<span>Название: <\/span><strong>(.*)<\/strong><br>/", $data ,$title);
		 preg_match("/<span>Автор: <\/span>(.*)<span>Название:/", $data ,$author);
		 $author[1] = trim(strip_tags($author[1]));
		 preg_match("/<span>Издательство: <\/span>(.*)<br> <span>Год:/", $data ,$publishing);
		 $publishing[1] = trim($publishing[1]); 
		 preg_match("/<span>Год: <\/span>([0-9]*)/", $data ,$year);
		 $year = str_pad($year[1], 4, "1", STR_PAD_LEFT);
		 preg_match("/Жанр (.*)<\/p> <h2/", $data ,$genre);
		 $genre = $dBgenre->findBy(array('title'=>"like '%".trim($genre[1])."%'"));
		 preg_match("/<span>ISBN: <\/span>(.*)<br> <span>Страниц:/", $data ,$isbn);
		 $isbn = trim($isbn[1]);
		 preg_match("/series-books.php\?id=(\d*)/", $data ,$series); 
		 $series = ($series)?$series[1]:null;	 
		 preg_match("/<p class=\"span_str\">(.*)В нашей библиотеке/", $data ,$description); 
		 $description = $description[1];
		 
		 
		$data = array(
			'title'=>$title[1],
			'author'=>$author[1],
			'publishing'=>$publishing[1],
			"year"=>($year < 1970)?1970:$year,
			'genry'=>(int)$genre[0]['id'],
			'isbn' => $isbn,
			'series' => $series,
			'description' => $description
		);	
	}
	if($id and $data['title']){
		$insert = array();
		$insert['title'] = $data['title'];
		$insert['id'] = $id;
		($data['author'])?$insert['author'] = $data['author']:'';
		($data['publishing'])?$insert['publishing'] = $data['publishing']:'';
		($data['isbn'])?$insert['isbn'] = $data['isbn']:'';
		($data['year'])?$insert['year'] = $data['year']:'';
		($data['genry'])?$insert['genre_id'] = $data['genry']:'';
		($data['series'])?$insert['series_id'] = $data['series']:'';
		($data['description'])?$insert['description'] = $data['description']:'';
		
		$dBbooks->insert($insert,false,false);
	}
}
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
grubb_book($dBbooks,$dBgenre);
?>
